package com.comtrade.activities;

import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.comtrade.ilserver.tasks.ConnectTask;
import com.comtrade.ilserver.tasks.User;
import com.example.beaconapk.R;



public class LoginActivity extends Activity  {

	
	EditText eTUser,eTPass,eTServerURL;
	Button logIn,createAcc;
	
	public static final String MyPREFERENCES="MyPrefs";
	public static final String URL="URL";
	public static final String Name="Username"; 
	public static final String Password="Passwd";
	public String etServerURL;
	public String etPass;
	public String etUser;
	public int k;
	SharedPreferences sharedpreferences;
	public User u;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login); 
		
		
		eTServerURL = (EditText) findViewById(R.id.et_serverURL);
		eTUser = (EditText) findViewById(R.id.et_user);
		eTPass = (EditText) findViewById(R.id.et_pass);
		logIn = (Button) findViewById(R.id.bLogIn);
		createAcc = (Button) findViewById(R.id.bCreateAcc);
		

		
		sharedpreferences=getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
		if(sharedpreferences.contains(URL))
			eTServerURL.setText(sharedpreferences.getString(URL," "));
		if(sharedpreferences.contains(Name))
			eTUser.setText(sharedpreferences.getString(Name," "));
		if(sharedpreferences.contains(Password))
			eTPass.setText(sharedpreferences.getString(Password," "));
				
		
		
	
		
		logIn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				etUser = eTUser.getText().toString();
				etPass = eTPass.getText().toString();
				etServerURL ="http://"+eTServerURL.getText().toString()+":8080/ils/rest/signin";
				Log.d("TAGURL",etServerURL);
		
				if(!etServerURL.trim().isEmpty()){
				
					if(!etUser.trim().isEmpty()){

						
						if(etPass.trim().length()>=5 && !etPass.trim().isEmpty()){
							
						
							Log.d("TAG", "Pre Connect");
							ConnectTask ct = new ConnectTask();
							ct.setUsername(etUser);
							ct.setPassword(etPass);
							ct.execute(etServerURL);
							Log.d("TAG", "execute");
							String json = null;
							try {
								Log.d("ulaz", "bla");
							
								json = ct.get();
								//Log.d("ulaz", ct.get().toString());
								k = 1;
							
								
							} catch (InterruptedException e) {
								 k = 0;
								e.printStackTrace();
							} catch (ExecutionException e) {
								 k = 0;
								e.printStackTrace();
							}//vraceni JSON 
							if (json == null) {
								Toast.makeText(getApplicationContext(), "Korisnik ne postoji u bazi.", Toast.LENGTH_SHORT).show();
								return;}
							
							String Url=eTServerURL.getText().toString();
							String n=eTUser.getText().toString();
							String pass=eTPass.getText().toString();
							Editor editor=sharedpreferences.edit();
							editor.putString(URL, Url);
							editor.putString(Name, n);
							editor.putString(Password, pass);
							editor.commit();
							
							
							u = User.fromJSON(json);
							u.getFirstname();
							Log.d("USER",u.getFirstname());
							
							Log.d("ROLES",""+ u.getRoles().size());
							
							Log.d("tag", u.getRoles().toString());
						
							
							
								
							if(k==1 ){
							
							
								 //Administrator	

		
			        			if(u.getRoles().size() == 3){
			        				Log.d("ROLES131231","Usao ovde 1");
									  Intent a = new Intent(LoginActivity.this, GuideActivity.class);
					       				a.putExtra("Account","Administrator");
					       				a.putExtra(User.EXTRA, u);
					       				startActivity(a);
									
								}
								
			        		
								
			        			//ima samo monitor
			        			
								else if(u.getRoles().size() == 1 && u.getRoles().contains("monitoring_officer")){
									
									Log.d("ROLES123123","Usao ovde 2");
									
									  Intent a = new Intent(LoginActivity.this, GuideActivity.class);
					       				a.putExtra("Account","Monitor");
					       				a.putExtra(User.EXTRA, u);
					       				startActivity(a);
									
									
								}
			        			
						
			        			//ima samo device
			        			
								else if(u.getRoles().size() == 1 && u.getRoles().contains("client")){
							
									Log.d("ROLES123123","Usao ovde 3");
									
									  Intent a = new Intent(LoginActivity.this, GuideActivity.class);
					       				a.putExtra("Account","Device");
					       				
					       				a.putExtra(User.EXTRA, u);
					       				startActivity(a);
									
								}
								
								
								
			        			
			        			
								else if(u.getRoles().size() ==2){	
								
									Log.d("ROLES123123","Usao ovde 4");
									AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
									final AlertDialog dialog = builder
											.setTitle("Role")
											.setMessage("Go to ")
											.setPositiveButton("Device",
													new DialogInterface.OnClickListener() {
												@Override
												public void onClick(DialogInterface dialog,
														int which) {
													Intent i = new Intent(LoginActivity.this, GuideActivity.class);
													i.putExtra("Account","Device");
													startActivity(i);
												}
											})
											.setNegativeButton("Monitor",
													new DialogInterface.OnClickListener() {
												@Override
												public void onClick(DialogInterface dialog,
														int which) {
													Intent i = new Intent(LoginActivity.this, GuideActivity.class);
													i.putExtra("Account","Monitor");
													Log.d("user",""+i.getParcelableExtra(User.EXTRA));
													i.putExtra(User.EXTRA, u);
													startActivity(i);
												}
											}).create();
									dialog.show();
										        Log.d("Dialog", "4");
									        
										        
								}else{
													
													 Log.d("Dialog", "Greska");
													 Toast.makeText(getApplicationContext(), "Korisnik ne postoji u bazi.", Toast.LENGTH_SHORT).show();
												}
								
								
								
							}
			        			
							
								
							}	
								
							
							
						
						else{
							
							Toast.makeText(getApplicationContext(), "Sifra mora imati najmanje 5 karaktera", Toast.LENGTH_SHORT).show();
							
							
						}
					
						
					}
					
					else{
						
						Toast.makeText(getApplicationContext(), "Niste uneli Username", Toast.LENGTH_SHORT).show();
						
						
					}
				
					
				}
				
				else{
					
					Toast.makeText(getApplicationContext(), "Niste uneli ServerURL", Toast.LENGTH_SHORT).show();
			
				}
			
				
			}
		

		});
		

		
		
		
	
	
	
	
		createAcc.setOnClickListener(new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			
			
			Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
			startActivity(i);
			
			
		}
	});
	
		
	}
	
	/*public void run(View view)
	{
		String Url=eTServerURL.getText().toString();
		String n=eTUser.getText().toString();
		String pass=eTPass.getText().toString();
		Editor editor=sharedpreferences.edit();
		editor.putString(URL, Url);
		editor.putString(Name, n);
		editor.putString(Password, pass);
		editor.commit();
				
	}*/

	
		
		
		
		@Override
		protected void onResume() {
			// TODO Auto-generated method stub
			super.onResume();
			sharedpreferences=getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
			if(sharedpreferences.contains(URL))
				eTServerURL.setText(sharedpreferences.getString(URL," "));
			if(sharedpreferences.contains(Name))
				eTUser.setText(sharedpreferences.getString(Name," "));
			if(sharedpreferences.contains(Password))
				eTPass.setText(sharedpreferences.getString(Password," "));
			
		}

	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}
